//
//  SnFlashView.swift
//  project
//
//  Created by 黄建华 on 2018/2/24.
//  Copyright © 2018年 黄建华. All rights reserved.
//

import UIKit

class SNFlashView: UIButton {

    var button = UIButton()
    var starting = false
    var valueLabel = UILabel()
    var heartCheckArray:Array<String> = []
    var oxCheckArray:Array<String> = []
    var bpCheckArray:Array<String> = []
    var timer:Timer!
    var flashImageView = UIImageView()
    override init(frame: CGRect) {
        super.init(frame: frame)
        creatView(frame: frame)
    }
    
    func  creatView (frame:CGRect)
    {
        button = CreatUIButton(frame: SMakeRect(x1: 0, y1: 0, width1: frame.width, height1: frame.height), text: "")
        button.setImage(SmakeImageWithName(imageName: "指纹"), for: .normal)
        self.addSubview(button)
        button.center = self.center
        button.addTarget(self, action: #selector(buttonTap), for: .touchUpInside)
        
        valueLabel = CreatUIlabel(frame: SMakeRect(x1: 0, y1: ScreenHeight/2, width1: 200, height1: 88), text: "-- \n bpm")
        valueLabel.font = SMakeFont(x: 28)
        valueLabel.numberOfLines = 2
        valueLabel.center = SmakePoint(x1: button.center.x, y1: button.center.y + 130)
        self.addSubview(valueLabel)
        
        weak var weakwelf=self
        SN_PublicClassSwift?.heartBlock = { (value:NSInteger) -> ()in
            weakwelf?.valueLabel.text = "\(value) \n bpm"
            weakwelf?.heartCheckArray.append("\(value)")
        }
        
        SN_PublicClassSwift?.oxBlock = { (value:NSInteger) -> ()in
            weakwelf?.valueLabel.text = "\(value) \n %"
            weakwelf?.oxCheckArray.append("\(value)")
        }
        
        SN_PublicClassSwift?.bpBlock = {(sbp:NSInteger,dbp:NSInteger) ->()in
            weakwelf?.valueLabel.text = "\(sbp) - \(dbp) \n mmHg"
            weakwelf?.bpCheckArray.append(String(sbp))
            weakwelf?.bpCheckArray.append(String(dbp))
            SN_KKSendClassSwift?.sendHeartStatus(false, type: (SN_PublicClassSwift?.checkType)!, withUpdate: { (object:Any,type:KKBLEAcceptType) in
                
            })
            self.EndAnimation()
            if ((SN_PublicClassSwift?.checkBlock) != nil) {
                SN_PublicClassSwift?.checkBlock(0)
            }
            //保存到本地数据并上传
            weakwelf?.saveCheckData()
        }
    }
    
        @objc func  buttonTap ()
        {
            if starting {
//                ShowMBProgressHUD(title: SMakeText(key: "正在体检"), time: 2.0)
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "体检页面通知"), object:nil)
            }
            else
            {
             self.StartAnimation()
             if SN_PublicClassSwift?.checkType==1 {
                valueLabel.text = "-- \n bpm"
             }
             if SN_PublicClassSwift?.checkType==2 {
                valueLabel.text = "-- \n %"
             }
             if SN_PublicClassSwift?.checkType==3{
                valueLabel.text = "-- \n mmHg"
                SN_PublicClassSwift?.bpValue = ""
             }
             heartCheckArray.removeAll()
             oxCheckArray.removeAll()
             bpCheckArray.removeAll()
             SN_KKSendClassSwift?.sendHeartStatus(true, type: (SN_PublicClassSwift?.checkType)!, withUpdate: { (object:Any,type:KKBLEAcceptType) in
                
            })
            }
        }
    
    func selectType(type:NSInteger) {
        
    }
    
    func StartAnimation ()
    {
        if SN_KKBleConnet?.isConnected == false {
            ShowMBProgressHUD(title: SMakeText(key: "设备未连接"), time: 2.0)
            return
        }
         UIApplication.shared.isIdleTimerDisabled = true
        ShowMBProgressHUD(title: SMakeText(key: "请等待..."), time: 2.0)
//        button.setImage(UIImage(named:""), for: .normal)
        let opts: UIViewAnimationOptions = UIViewAnimationOptions.autoreverse
        flashImageView = UIImageView(frame:button.frame)
        flashImageView.image = UIImage.gif(name: "心率240")
        flashImageView.tag = 100;
        if SN_PublicClassSwift?.checkType==1
        {
            flashImageView.image = UIImage.gif(name: "心率240")
        }
        if SN_PublicClassSwift?.checkType==2
        {
            flashImageView.image = UIImage.gif(name: "血氧240")
        }
        if SN_PublicClassSwift?.checkType==3
        {
            flashImageView.image = UIImage.gif(name: "血压240")
        }

        flashImageView.center = button.center
        button.addSubview(flashImageView)
        
        starting = true
        if ((SN_PublicClassSwift?.checkBlock) != nil) {
            SN_PublicClassSwift?.checkBlock(1)
        }
        
        var checkTime = 0.0;
        if (SN_PublicClassSwift?.checkType == 1 || SN_PublicClassSwift?.checkType == 2)
        {
            checkTime = 60.0;
        }
        else
        {
            checkTime = 66.0;
        }
        
        timer = Timer.scheduledTimer(timeInterval: checkTime, target:self, selector: #selector(timeRun), userInfo: nil, repeats: false)
    }
    @objc func timeRun(){
        flashImageView.removeFromSuperview()
        self.starting = false
        self.button.setImage(UIImage(named:"指纹"), for: .normal)
        SN_KKSendClassSwift?.sendHeartStatus(false, type: (SN_PublicClassSwift?.checkType)!, withUpdate: { (object:Any,type:KKBLEAcceptType) in
            
        })
        if ((SN_PublicClassSwift?.checkBlock) != nil) {
            SN_PublicClassSwift?.checkBlock(0)
        }
        //保存到本地数据并上传
        if((SN_PublicClassSwift?.checkType) != 3){
            self.saveCheckData()
        }
    }
    func saveCheckData() {
        UIApplication.shared.isIdleTimerDisabled = false
        if heartCheckArray.count>0
        {
             let tmodel = SN_PublicClassSwift?.todayHeart
             tmodel?.updateRealHeartDataEnd(heartCheckArray)
             HeartModel.updateCheckHeart()
        }
        
        if oxCheckArray.count>0
        {
            let tmodel = SN_PublicClassSwift?.todayOx
            tmodel?.updateRealOXEnd(oxCheckArray)
            OxModel.updateCheckOX()
        }
        
        if bpCheckArray.count>0
        {
            let tmodel = SN_PublicClassSwift?.todayBp
            tmodel?.updateRealBPDataEnd(bpCheckArray)
            BpModel.updateCheckBP()
        }
    }
    
    func EndAnimation ()
    {
        UIApplication.shared.isIdleTimerDisabled = false
        for view in button.subviews{
            if view.tag == 100
            {
                view.layer.removeAllAnimations()
                view.removeFromSuperview()
            }
        }
        timer.fireDate = Date.distantFuture
        flashImageView.removeFromSuperview()
        self.starting = false
        self.button.setImage(UIImage(named:"指纹"), for: .normal)
        SN_KKSendClassSwift?.sendHeartStatus(false, type: (SN_PublicClassSwift?.checkType)!, withUpdate: { (object:Any,type:KKBLEAcceptType) in
            
        })
        if ((SN_PublicClassSwift?.checkBlock) != nil) {
            SN_PublicClassSwift?.checkBlock(0)
        }
        //保存到本地数据并上传
        if((SN_PublicClassSwift?.checkType) != 3){
            self.saveCheckData()
        }
        ShowMBProgressHUD(title: SMakeText(key: "体检结束"), time: 0.5)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

